<template>
  <div class="container">
    <!-- 引用导航栏组件 -->
    <NavBar @view-history-questionnaire="viewHistoryQuestionnaire" />
   <div class="main-container">
    <!-- 左侧导航栏 -->
    <el-menu
      class="nav-menu"
      :default-active="activeTab"
      @select="handleTabSelect"
    >
      <el-menu-item index="current">当前预约</el-menu-item>
      <el-menu-item index="history">历史预约</el-menu-item>
    </el-menu>

    <!-- 右侧内容区域 -->
    <div class="content">
      <!-- 当前预约 -->
      <div v-if="activeTab === 'current'">
        <div v-if="userRole === 'VISITOR'">
          <el-card v-if="currentOrder.id">
            <template #header>
              <div class="card-header">
                <span>当前预约</span>
              </div>
            </template>
            <el-descriptions :column="1" border>
              <el-descriptions-item label="咨询师">
                {{ getConsultantName(currentOrder.consultantId) }}
              </el-descriptions-item>
              <el-descriptions-item label="预约时间">
                {{ formatTime(currentOrder.startTime) }} - {{ formatTime(currentOrder.endTime) }}
              </el-descriptions-item>
              <el-descriptions-item label="状态">
                {{ statusMap[currentOrder.status] }}
              </el-descriptions-item>
              <el-descriptions-item label="咨询方式">
                {{ orderTypeMap[currentOrder.orderType] }}
              </el-descriptions-item>
              <el-descriptions-item label="备注">
                {{ currentOrder.remark || "无" }}
              </el-descriptions-item>
            </el-descriptions>
            <el-button 
              type="danger" 
              @click="handleCancel(currentOrder.id)"
              style="margin-top: 20px;"
            >
              取消预约
            </el-button>
          </el-card>
          <el-empty v-else description="暂无当前预约" />
        </div>

        <!-- 咨询师视图 -->
        <div v-else>
          <el-card v-if="currentOrders.length > 0">
            <template #header>
              <div class="card-header">
                <span>待处理预约（{{ currentOrders.length }}）</span>
              </div>
            </template>
            <el-table :data="currentOrders">
              <el-table-column prop='nickname' label="用户名称" />
              <el-table-column label="预约时间">
                <template #default="{ row }">
                  {{ formatTime(row.startTime) }} - {{ formatTime(row.endTime) }}
                </template>
              </el-table-column>
              <el-table-column label="咨询方式">
                <template #default="{ row }">
                  {{ orderTypeMap[row.orderType] }}
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" />
              <el-table-column label="操作" width="180">
                <template #default="{ row }">
                  <el-button
                    type="success"
                    size="small"
                    @click="handleAccept(row.id)"
                  >
                    接受
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    @click="handleCancel(row.id)"
                  >
                    取消
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
          <el-empty v-else description="暂无待处理预约" />
        </div>
      </div>

      <!-- 历史预约 -->
      <div v-else>
        <el-card>
          <el-table :data="historyOrders" style="width: 100%">
            <el-table-column 
              :prop="userRole === 'VISITOR' ? 'consultantName' : 'nickname'"
              :label="userRole === 'VISITOR' ? '咨询师' : '用户'"
            />
            <el-table-column label="预约时间">
              <template #default="{ row }">
                {{ formatTime(row.startTime) }} - {{ formatTime(row.endTime) }}
              </template>
            </el-table-column>
            <el-table-column label="状态">
              <template #default="{ row }">
                {{ statusMap[row.status] }}
              </template>
            </el-table-column>
            <el-table-column label="咨询方式">
              <template #default="{ row }">
                {{ orderTypeMap[row.orderType] }}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
          </el-table>
          <el-pagination
            :current-page="pagination.current"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            @current-change="handlePageChange"
            :page-sizes="[15, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
          />
        </el-card>
      </div>
    </div>
   </div>
    <!-- 取消理由对话框 -->
    <el-dialog v-model="cancelDialogVisible" title="取消预约">
      <el-input
        v-model="cancelReason"
        type="textarea"
        placeholder="请输入取消理由"
      />
      <template #footer>
        <el-button @click="cancelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCancel">确定</el-button>
      </template>
    </el-dialog>
  </div>

</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs';
import NavBar from './NavBar.vue';

const userRole = ref(localStorage.getItem('role'))
const activeTab = ref('current')
const cancelDialogVisible = ref(false)
const cancelReason = ref('')
const currentOrderId = ref('')

// 数据映射
const statusMap = {
  TODO: '待确认',
  RESERVED: '已预约',
  CANCELED: '已取消',
  DONE: '已完成',
  EXPIRED: '已过期',
  REMOVE: '删除'
}

const orderTypeMap = {
  ONLINE: '线上',
  OFFLINE: '线下'
}

// 来访者当前预约
const currentOrder = ref({})

// 咨询师当前预约
const currentOrders = ref([])

// 历史预约
const historyOrders = ref([])

const pagination = ref({
  current: 1,
  pageSize: 15,
  total: 0
})

// 获取咨询师名称
const getConsultantName =(id) => {
    console.log(`${id}`)
  return localStorage.getItem(`${id}`) || '未知咨询师'
}

// 时间格式化
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 处理预约操作
const handleCancel = (orderId) => {
  currentOrderId.value = orderId
  cancelDialogVisible.value = true
}

const confirmCancel = async () => {
  try {
    await axios.post('/order/accept', {
      orderId: currentOrderId.value,
      acceptStatus: '0',
      cancelMsg: cancelReason.value
    }, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    ElMessage.success('取消成功')
    loadData()
    cancelDialogVisible.value = false
    cancelReason.value = ''
  } catch (error) {
    ElMessage.error('取消失败')
  }
}

const handleAccept = async (orderId) => {
  try {
    await axios.post('/order/accept', {
      orderId,
      acceptStatus: '1',
      cancelMsg: ''
    }, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    ElMessage.success('接受成功')
    loadData()
  } catch (error) {
    ElMessage.error('接受失败')
  }
}

// 加载数据
const loadData = async () => {
  try {
    if (activeTab.value === 'current') {
      if (userRole.value === 'VISITOR') {
        const res = await axios.get('/order/orderLast', {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        currentOrder.value = res.data
        console.log('当前预约：', currentOrder.value);  // 调试用，查看数据
      } else {
        console.log('当前预约：', userRole.value);  // 调试用，查看数据
        const res = await axios.post('/order/list/page', {
          current: 0,
          pageSize: 15,
          consultantId: localStorage.getItem('userId'),
          userId: ''
        }, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem('token')}`
          }
        })
        currentOrders.value = res.data.content.filter(item => item.status === 'TODO').map(item=>{
         const consultantName = getConsultantName(item.consultantId);
         const nickname = item.nickName;
         console.log("昵称为： ",`${nickname}`)
          console.log("咨询师名称为: ",`${consultantName}`);
        return {
            ...item,
            consultantName,
            nickname
        }
      })
      }
    } else {
      const params = {
        current: pagination.value.current - 1,
        pageSize: pagination.value.pageSize,
      }
      
      if (userRole.value === 'VISITOR') { 
        params.userId = localStorage.getItem('userId')
        params.consultantId = ''
      } else {
        params.consultantId = localStorage.getItem('userId')
        params.userId = ''
      }

      const res = await axios.post('/order/list/page', params, {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('token')}`
        }
      })
      historyOrders.value = res.data.content.filter(item => item.status !== 'TODO').map(item=>{
         const consultantName = getConsultantName(item.consultantId);
         const nickname = item.nickName;
         console.log("昵称为： ",`${nickname}`)
          console.log("咨询师名称为: ",`${consultantName}`);
        return {
            ...item,
            consultantName,
            nickname
        }
      })
      pagination.value.total = res.data.totalElements
    }
  } catch (error) {
    console.error('数据加载失败:', error)
  }
}

// 初始化加载
onMounted(() => {
  loadData()
})

// 分页处理
const handlePageChange = (page) => {
  pagination.value.current = page
  loadData()
}

// 切换标签
const handleTabSelect = (key) => {
  activeTab.value = key
  loadData()
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column; /* 改为垂直布局 */
  min-height: 100vh;
}
.main-container {
  display: flex;
  flex: 1;
  min-height: 20px;
}

.nav-menu {
  width: 200px;
  height: auto;
  background-color: #f7f7f7; /* 左侧菜单背景色 */
}

.content {
  flex: 1;
  padding: 20px;
  background-color: #fff; /* 右侧内容背景色 */
  overflow: auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>